package com.aimashi.aimashibackendjudgeservice.judge.codesandbox.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.aimashi.aimashibackcommon.common.ErrorCode;
import com.aimashi.aimashibackcommon.exception.BusinessException;
import com.aimashi.aimashibackendjudgeservice.judge.codesandbox.CodeSandbox;
import com.aimashi.aimashibackmodel.model.codesandbox.ExecuteCodeRequest;
import com.aimashi.aimashibackmodel.model.codesandbox.ExecuteCodeResponse;
import com.alibaba.excel.util.StringUtils;

public class RemoteCodeSandbox implements CodeSandbox {

    private static final String AUTH_REQUEST_HEARD = "auth";
    private static final String AUTH_REQUEST_SECRET = "secretKey";

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        System.out.println("远程代码沙箱");
        String url = "http://localhost:8090/executeCode";
        String jsonStr = JSONUtil.toJsonStr(executeCodeRequest);
        String responseStr = HttpUtil.createPost(url)
                .header(AUTH_REQUEST_HEARD, AUTH_REQUEST_SECRET)
                .body(jsonStr)
                .execute()
                .body();
        if (StringUtils.isBlank(responseStr)){
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR,"executeCode RemoteCodeSandbox executeCode error");
        }

        return JSONUtil.toBean(responseStr, ExecuteCodeResponse.class);
    }
}
